import { Injectable } from '@nestjs/common';
import * as svgCaptcha from 'svg-captcha';
import { RedisService } from '@/modules/redis/redis.service';

@Injectable()
export class CaptchaService {
  constructor(private readonly redisService: RedisService) {}

  /**
   * 生成验证码
   */
  async generateCaptcha() {
    const captcha = svgCaptcha.create({
      size: 4, // 验证码长度
      noise: 2, // 干扰线条数
      color: true, // 验证码字符颜色
      background: '#f0f2f5', // 背景颜色
    });

    const captchaId = `captcha:${Date.now()}`;
    // 将验证码存入Redis，设置60秒过期
    await this.redisService.set(captchaId, captcha.text.toLowerCase(), 60);

    return {
      captchaId,
      captchaUrl: `data:image/svg+xml;base64,${Buffer.from(captcha.data).toString('base64')}`,
    };
  }

  /**
   * 验证验证码
   */
  async validateCaptcha(captchaId: string, captchaCode: string): Promise<boolean> {
    if (!captchaId || !captchaCode) {
      return false;
    }

    const correctCode = await this.redisService.get(captchaId);
    if (!correctCode) {
      return false;
    }

    // 验证后立即删除验证码
    await this.redisService.del(captchaId);
    
    return correctCode === captchaCode.toLowerCase();
  }
} 